package longshu.data.config;

import org.apache.coyote.http11.Http11Nio2Protocol;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.io.File;

/**
 * DataTesting
 *
 * @author LongShu 2018/01/18
 */
@Configuration
@EnableCaching
@ComponentScan(basePackages = "longshu.data")
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class DataTestingConfiguration {

    @Bean
    public TomcatEmbeddedServletContainerFactory servletContainerFactory() {
        TomcatEmbeddedServletContainerFactory containerFactory = new TomcatEmbeddedServletContainerFactory();

        containerFactory.setProtocol(Http11Nio2Protocol.class.getName());

        File baseDir = createTempDir("tomcat.data_testing." + containerFactory.getPort());
        containerFactory.setBaseDirectory(baseDir);
        File docBase = createTempDir("tomcat-docbase.data_testing" + containerFactory.getPort());
        containerFactory.setDocumentRoot(docBase);

        return containerFactory;
    }

    private File createTempDir(String name) {
        File tempDir = new File(System.getProperty("java.io.tmpdir"), name);
        if (!tempDir.exists()) {
            tempDir.mkdir();
            tempDir.deleteOnExit();
        }
        return tempDir;
    }

}
